package util
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.system.LoaderContext;
	import flash.ui.ContextMenu;
	import flash.utils.ByteArray;
	
	import util.err.FileNotExistErr;
	import util.err.FileNotFileErr;

	public class LocalSwfoader
	{
		private var _url:String;
		
		private var _callBack:Function;
		
		/**
		 *  
		 * @param url	swf的路径
		 * @param callBack	加载完毕后的回调,函数格式为 function( loader:LoaderInfo ):void; 其中loader参数为加载内容的LoaderInfo对象.
		 * 
		 */		
		public function LocalSwfoader( url:String, callBack:Function )
		{
			if( !url || url.length == 0 )
			{
				throw new FileNotFileErr( url );
			}
			
			this._url = url;
			
			this._callBack = callBack;
			
		}
		
		public function load():void
		{
			var swfFile:File = new File( _url );
			
			if( !swfFile.exists )
			{
				throw new FileNotExistErr( swfFile );
			}
			
			if( swfFile.isDirectory )
			{
				throw new FileNotFileErr( swfFile );
			}
			
			var stream:FileStream = new FileStream();
			
			stream.addEventListener(Event.COMPLETE, fileCompleteHandler)

			stream.openAsync( swfFile, FileMode.READ );
		}
		
		private function fileCompleteHandler( event:Event ):void
		{
			var stream:FileStream = event.currentTarget as FileStream;
			
			var swfBytes: ByteArray = new ByteArray();
			stream.readBytes( swfBytes );
			stream.close();
			
			var swfHandler:Loader = new Loader();
			
			swfHandler.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );
			
			var context:LoaderContext = new LoaderContext();
			context.allowLoadBytesCodeExecution = true;
			swfHandler.loadBytes(swfBytes, context);
		}
		
		
		private function onComplete( e:Event ):void
		{
			if( _callBack is Function )
			{
				_callBack( e.currentTarget );
				
				
			}
		}
	
		
	}
}